﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Common;
using Vit.Common;

namespace Vit.Data
{
    public class DbConnectionWrapper : DbConnection
    {
        private DbConnection wrappedConnection;

        public DbConnectionWrapper(DbConnection connection)
        {
            this.wrappedConnection = connection;
            connection.StateChange += new StateChangeEventHandler(connection_StateChange);
        }

        protected void connection_StateChange(object sender, StateChangeEventArgs e)
        {
            foreach (IDbConnectionVisitor visitor in DbConnectionVisitorManager.Visitors)
            {
                if (visitor.IsVisiting(this))
                    visitor.OnConnectionStateChange(sender, e);
            }
        }

        protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel)
        {
            return new DbTransactionWrapper(this.wrappedConnection.BeginTransaction(isolationLevel), this);
        }

        public override void ChangeDatabase(string databaseName)
        {
            this.wrappedConnection.ChangeDatabase(databaseName);
        }

        public override void Close()
        {
            this.wrappedConnection.Close();
        }

        public override string ConnectionString
        {
            get
            {
                return this.wrappedConnection.ConnectionString;
            }
            set
            {
                this.wrappedConnection.ConnectionString = value;
            }
        }

        protected override DbCommand CreateDbCommand()
        {
            DbCommand cmd = this.wrappedConnection.CreateCommand();
            return new DbCommandWrapper(cmd, this);
        }

        public override string DataSource
        {
            get { return this.wrappedConnection.DataSource; }
        }

        public override string Database
        {
            get { return this.wrappedConnection.Database; }
        }

        public override void Open()
        {
            this.wrappedConnection.Open();
        }

        public override string ServerVersion
        {
            get { return this.wrappedConnection.ServerVersion; }
        }

        public override ConnectionState State
        {
            get { return this.wrappedConnection.State; }
        }
    }
}
